package main.java.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import main.java.domain.User;
import main.java.services.LoginService;
import main.java.services.impl.LoginServiceImpl;

/*
 	按住ctrl点击相应的类或方法可以查看源码
 	如果HttpServlet的源码无法查看，参考：https://blog.csdn.net/pfdvnah/article/details/106043807
 */
public class LoginServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private LoginService loginService=new LoginServiceImpl();
	/* 重写 父类HttpServlet 的 doGet 和 doPost 方法 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		/* 接收post请求的参数 */
		String tel = req.getParameter("tel");
		String pwd = req.getParameter("pwd");
		User user=new User(tel,pwd);
		
		/*调用登录逻辑*/
		boolean flag=loginService.login(user);
		String result="";
		if(flag)
			result="Success";
		else
			result="Failed";
		
		/* 将结果序列化为json并返回给前端，这里用了一个json相关的jar包 */
		ObjectMapper mapper=new ObjectMapper();
		String json = mapper.writeValueAsString(result);//将结果序列化为json
        System.out.println(json);
		
		/*将json数据返回给前端*/
        resp.setContentType("application/json;charset=utf-8");	//1.设置content-type(内容类型，浏览器会根据内容类型解析结果)
        resp.getWriter().write(json);							//2.将json数据写回前端
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
